#ifndef _THREAD_HPP__
#define _THREAD_HPP__

#include <iostream>
#include <string>
#include <pthread.h>
#include <functional>
#include <sys/types.h>
#include <unistd.h>

namespace ThreadModule
{
    static int number = 1;
    using func_t = std::function<void()>;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOP
    };
    class mythread
    {
    private:
        static void *routine(void *args)
        {
            mythread *t = static_cast<mythread *>(args);
            t->_status = TSTATUS::RUNNING;
            t->_func();
            return nullptr;
        }
        void EnableDetach(){_joinable = false;}
    public:
        mythread(func_t func)
            : _joinable(true), _func(func), _status(TSTATUS::NEW)
        {
            _pid = getpid();
            _name = "Thread-" + std::to_string(number++);
        }

        bool Start()
        {
            if (_status != TSTATUS::RUNNING)
            {
                int n = pthread_create(&_tid, nullptr, routine, this);
                if (n != 0)
                {
                    return false;
                }
                _status = TSTATUS::RUNNING;
                return true;
            }
            return false;
        }
        bool Stop()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;
                return true;
            }
            return false;
        }
        bool Join()
        {
            if (_status == TSTATUS::RUNNING)
            {
                int n = pthread_join(_tid, nullptr);
                if (n != 0)
                    return false;
                _status = TSTATUS::STOP;

                return true;
            }
            return false;
        }
        void Detach()
        {
            EnableDetach();
            pthread_detach(_tid);
        }
        std::string Name()
        {return _name;}
    private:
        pid_t _pid;
        pthread_t _tid;
        std::string _name;
        bool _joinable;
        func_t _func;
        TSTATUS _status;
    };

};
#endif